import { Controller } from 'egg';
import { RESULT_CODE } from '../utils/constants/code';
export default class AuthController extends Controller {
  /**
   * 用户注册
   */
  async register() {
    const { ctx } = this;

    // 参数验证
    const rule = {
      mobile: { type: 'string', format: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
      user_name: { type: 'string', min: 2, max: 20, message: '昵称长度为2-20个字符' },
      password: { type: 'string', min: 6, max: 20, message: '密码长度为6-20个字符' },
    };

    ctx.validate(rule);

    const { mobile, user_name, password } = ctx.request.body;

    try {
      const result = await ctx.service.auth.register(mobile, user_name, password);
      
      ctx.body = {
        code: 200,
        message: '注册成功',
        data: result,
      };
    } catch (error: any) {
      ctx.throw(400, error.message);
    }
  }

  /**
   * 用户登录
   */
  async login() {
    const { ctx } = this;

    // 参数验证
    const rule = {
      mobile: { type: 'string', format: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
      password: { type: 'string', required: true, message: '密码不能为空' },
    };

    ctx.validate(rule);

    const { mobile, password } = ctx.request.body;

    try {
      const result = await ctx.service.auth.login(mobile, password);
      
      ctx.body = {
        code: 200,
        message: '登录成功',
        data: result,
      };
    } catch (error: any) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**
   * 获取用户信息
   */
  async getUserInfo() {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    try {
      const result = await ctx.service.auth.getUserInfo(userId);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error: any) {
      ctx.throw(400, error.message);
    }
  }
}